package com.easyjava.builder;

import com.easyjava.bean.Constants;
import com.easyjava.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class BuildApplication {
    private static final Logger logger = LoggerFactory.getLogger(BuildApplication.class);

    public static void execute() {
        String BasePath = (Constants.PATH_BASE + "/" + Constants.PACKAGE_BASE).replace(".", "/");
        File folder = new File(BasePath);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        String packageBase = Constants.PACKAGE_BASE;
        String className = packageBase.substring(packageBase.indexOf(".") + 1);
        className = StringUtils.uperCaseFirstLetter(className) + "Application";
        File poFile = new File(folder, className + ".java");

        OutputStream out = null;
        OutputStreamWriter outw = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(poFile);
            outw = new OutputStreamWriter(out, "utf-8");
            bw = new BufferedWriter(outw);

            bw.write("package " + Constants.PACKAGE_BASE + ";");
            bw.newLine();
            bw.newLine();
            bw.write("import org.mybatis.spring.annotation.MapperScan;");
            bw.newLine();
            bw.write("import org.springframework.boot.SpringApplication;");
            bw.newLine();
            bw.write("import org.springframework.boot.autoconfigure.SpringBootApplication;");
            bw.newLine();
            bw.newLine();

            BuildComment.createClassComment(bw, "启动类");
            bw.write("@SpringBootApplication(scanBasePackages = {\"" + packageBase + "\"})");
            bw.newLine();
            bw.write("@MapperScan(basePackages = \"" + packageBase + ".mappers\")");
            bw.newLine();
            bw.write("public class " + className + " {");
            bw.newLine();
            bw.write("\tpublic static void main(String[] args) {");
            bw.newLine();
            bw.write("\t\tSpringApplication.run(" + className + ".class, args);");
            bw.newLine();
            bw.write("\t}");
            bw.newLine();
            bw.write("}");
            bw.flush();
        } catch (Exception e) {
            logger.error("创建 Service 失败", e);
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (outw != null) {
                try {
                    outw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
